Page({
  data: {
    selectedStocks: [],
    searchResult: []
  },

  onLoad: function() {
    const openid = wx.getStorageSync('openid');
    wx.cloud.callFunction({
      name: 'getStock', // 云函数的名称
      data: {
        openid: openid // 替换为实际用户的 openid
      },
      success: res => {
        console.log('调用云函数成功:', res);
        if (res.result.selectedStocks) {
          this.setData({
            selectedStocks: res.result.selectedStocks
          });
          this.fetchStockData(res.result.selectedStocks);
        }
      },
      fail: err => {
        console.error('调用云函数失败:', err);
      }
    });
  },

  fetchStockData: function(stockCodes) {
    const that = this;
    const searchResult = [];

    stockCodes.forEach((code, index) => {
      wx.request({
        url: `https://hq.sinajs.cn/list=${code}`,
        success: (res) => {
          const dataStr = res.data.match(/"([^"]*)"/)[1];
          const dataArr = dataStr.split(',');
          const stockName = dataArr[0];
          const yesterdayClose = parseFloat(dataArr[2]).toFixed(2);
          const currentPrice = parseFloat(dataArr[3]).toFixed(2);
          const priceChange = (((currentPrice-yesterdayClose) /   yesterdayClose) * 100).toFixed(2) + '%';
            searchResult.push({
            code:code,
            name: stockName,
            currentPrice: currentPrice,
            priceChange:priceChange
          });

          // 更新 searchResult 数组
          if (index === stockCodes.length - 1) {
            that.setData({
              searchResult: searchResult
            });
            console.log(searchResult)
          }
        },
        fail: (err) => {
          console.error(`获取股票代码 ${code} 数据失败:`, err);
        }
      });
    });
  },
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
   // 跳转到详细页面
   detail: function(event) {
    const stockCode = event.currentTarget.dataset.item;
    console.log(stockCode)
    wx.navigateTo({
      url: `/pages/stock/stock?stockCode=${stockCode}`
    });
  }
})
